package http.zjitc.net.http;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpActivity extends AppCompatActivity  implements View.OnClickListener {
    private ImageView iv_http;
    private Button btn_http;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ok_http);
        init();
        btn_http.setOnClickListener(this);
    }

    private void init() {
        iv_http=findViewById(R.id.iv_http);
        btn_http=findViewById(R.id.btn_http);
    }

    @Override
    public void onClick(View v) {
        request();
    }

    private void request() {
        //1.创建Request对象，设置url地址，调用请求
        Request.Builder requestBuilder=new Request.Builder().url("http://vux-gal.sunteorum.com/2015-00/FtozXhq0RgKtuQaakGr3nidlFCAT");
        requestBuilder.method("GET",null);
        Request request=requestBuilder.build();
        //2.创建okHttpClient对象
        OkHttpClient okHttpClient=new OkHttpClient();
        //3.创建call对象
        Call call=okHttpClient.newCall(request);
        //4.调用call方法，回调
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                byte[] bytes=response.body().bytes();

                final Bitmap bitmap=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        iv_http.setImageBitmap(bitmap);
                    }
                });
            }
        });
    }
}
